package com.ruoyi.business.system;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReadWriteLock;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;

/**
 * 系统信息控制器
 * 提供系统相关的工具方法
 * 
 * @author ruoyi
 * @date 2024-01-01
 */
@RestController
@RequestMapping("/business/system")
public class SystemInfoController extends BaseController {
    
    // 缓存网络接口信息，避免重复扫描
    private static final Map<String, Object> NETWORK_CACHE = new ConcurrentHashMap<>();
    private static final AtomicReference<Long> LAST_UPDATE_TIME = new AtomicReference<>(0L);
    private static final ReadWriteLock CACHE_LOCK = new ReentrantReadWriteLock();
    
    // 缓存过期时间：30秒
    private static final long CACHE_EXPIRE_TIME = 30000L;
    
    // 预定义的IP地址类型映射，避免重复计算
    private static final Map<String, String> IP_TYPE_CACHE = new ConcurrentHashMap<>();
    
    static {
        // 预填充常见的内网IP段
        for (int i = 0; i <= 255; i++) {
            IP_TYPE_CACHE.put("192.168." + i + ".", "内网");
        }
        for (int i = 0; i <= 255; i++) {
            IP_TYPE_CACHE.put("10." + i + ".", "内网");
        }
        for (int i = 16; i <= 31; i++) {
            IP_TYPE_CACHE.put("172." + i + ".", "内网");
        }
        // 特殊IP段
        IP_TYPE_CACHE.put("127.", "特殊");
        IP_TYPE_CACHE.put("169.254.", "特殊");
    }
    
    /**
     * 获取本机IP地址信息（优化版本）
     */
    @PreAuthorize("@ss.hasPermi('business:system:query')")
    @GetMapping("/localIp")
    public AjaxResult getLocalIPAddresses() {
        try {
            // 尝试从缓存获取
            Map<String, Object> cachedResult = getCachedResult();
            if (cachedResult != null) {
                return AjaxResult.success("获取本机IP地址成功(缓存)", cachedResult);
            }
            
            // 缓存未命中，异步更新缓存
            CompletableFuture.runAsync(this::updateNetworkCache);
            
            // 返回快速结果（使用上次的缓存或默认值）
            Map<String, Object> quickResult = getQuickResult();
            return AjaxResult.success("获取本机IP地址成功(快速)", quickResult);
            
        } catch (Exception e) {
            return AjaxResult.error("获取本机IP地址失败: " + e.getMessage());
        }
    }
    
    /**
     * 强制刷新IP地址缓存
     */
    @PreAuthorize("@ss.hasPermi('business:system:query')")
    @GetMapping("/localIp/refresh")
    public AjaxResult refreshLocalIPAddresses() {
        try {
            // 清除缓存
            clearNetworkCache();
            
            // 同步更新缓存
            updateNetworkCache();
            
            // 获取最新结果
            Map<String, Object> result = getCachedResult();
            if (result != null) {
                return AjaxResult.success("IP地址缓存刷新成功", result);
            } else {
                return AjaxResult.error("IP地址缓存刷新失败");
            }
        } catch (Exception e) {
            return AjaxResult.error("IP地址缓存刷新失败: " + e.getMessage());
        }
    }
    
    /**
     * 从缓存获取结果
     */
    private Map<String, Object> getCachedResult() {
        CACHE_LOCK.readLock().lock();
        try {
            Long lastUpdate = LAST_UPDATE_TIME.get();
            if (lastUpdate > 0 && System.currentTimeMillis() - lastUpdate < CACHE_EXPIRE_TIME) {
                return (Map<String, Object>) NETWORK_CACHE.get("result");
            }
            return null;
        } finally {
            CACHE_LOCK.readLock().unlock();
        }
    }
    
    /**
     * 获取快速结果（使用缓存或默认值）
     */
    private Map<String, Object> getQuickResult() {
        Map<String, Object> cachedResult = getCachedResult();
        if (cachedResult != null) {
            return cachedResult;
        }
        
        // 返回默认结果
        Map<String, Object> defaultResult = new HashMap<>();
        defaultResult.put("ipList", new ArrayList<>());
        defaultResult.put("total", 0);
        defaultResult.put("recommendedIP", "127.0.0.1");
        defaultResult.put("message", "正在后台更新IP地址信息，请稍后刷新");
        return defaultResult;
    }
    
    /**
     * 更新网络缓存
     */
    @Async
    public void updateNetworkCache() {
        CACHE_LOCK.writeLock().lock();
        try {
            Map<String, Object> result = scanNetworkInterfaces();
            NETWORK_CACHE.put("result", result);
            LAST_UPDATE_TIME.set(System.currentTimeMillis());
        } catch (Exception e) {
            // 记录错误但不影响主流程
            System.err.println("更新网络缓存失败: " + e.getMessage());
        } finally {
            CACHE_LOCK.writeLock().unlock();
        }
    }
    
    /**
     * 清除网络缓存
     */
    private void clearNetworkCache() {
        CACHE_LOCK.writeLock().lock();
        try {
            NETWORK_CACHE.clear();
            LAST_UPDATE_TIME.set(0L);
        } finally {
            CACHE_LOCK.writeLock().unlock();
        }
    }
    
    /**
     * 扫描网络接口（优化版本）
     */
    private Map<String, Object> scanNetworkInterfaces() throws SocketException {
        Map<String, Object> result = new HashMap<>();
        List<Map<String, String>> ipList = new ArrayList<>();
        
        // 获取所有网络接口
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = networkInterfaces.nextElement();
            
            // 快速跳过回环接口和未启用的接口
            if (networkInterface.isLoopback() || !networkInterface.isUp()) {
                continue;
            }
            
            // 获取该接口的所有IP地址
            Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
            
            while (inetAddresses.hasMoreElements()) {
                InetAddress inetAddress = inetAddresses.nextElement();
                
                // 只处理IPv4地址
                String hostAddress = inetAddress.getHostAddress();
                if (hostAddress.indexOf(':') == -1) {
                    String interfaceName = networkInterface.getDisplayName();
                    
                    // 使用缓存的IP类型判断
                    String ipType = getIPTypeFast(hostAddress);
                    
                    Map<String, String> ipInfo = new HashMap<>();
                    ipInfo.put("ip", hostAddress);
                    ipInfo.put("interface", interfaceName);
                    ipInfo.put("type", ipType);
                    ipInfo.put("hostname", inetAddress.getHostName());
                    
                    ipList.add(ipInfo);
                }
            }
        }
        
        // 快速排序：内网IP优先
        ipList.sort((a, b) -> {
            String typeA = a.get("type");
            String typeB = b.get("type");
            
            // 内网IP优先级最高
            if ("内网".equals(typeA) && !"内网".equals(typeB)) return -1;
            if (!"内网".equals(typeA) && "内网".equals(typeB)) return 1;
            
            // 外网IP次之
            if ("外网".equals(typeA) && !"外网".equals(typeB)) return -1;
            if (!"外网".equals(typeA) && "外网".equals(typeB)) return 1;
            
            return 0;
        });
        
        result.put("ipList", ipList);
        result.put("total", ipList.size());
        
        // 推荐IP地址（第一个内网IP或第一个可用IP）
        String recommendedIP = getRecommendedIPFast(ipList);
        result.put("recommendedIP", recommendedIP);
        
        return result;
    }
    
    /**
     * 快速判断IP地址类型（使用缓存）
     */
    private String getIPTypeFast(String ipAddress) {
        // 先检查缓存
        String cachedType = IP_TYPE_CACHE.get(ipAddress);
        if (cachedType != null) {
            return cachedType;
        }
        
        // 检查内网IP段
        if (ipAddress.startsWith("192.168.") || 
            ipAddress.startsWith("10.") || 
            (ipAddress.startsWith("172.") && isInRangeFast(ipAddress, "172.16.0.0", "172.31.255.255"))) {
            return "内网";
        } else if (ipAddress.startsWith("127.") || ipAddress.startsWith("169.254.")) {
            return "特殊";
        } else {
            return "外网";
        }
    }
    
    /**
     * 快速判断IP地址是否在指定范围内
     */
    private boolean isInRangeFast(String ip, String startIP, String endIP) {
        try {
            long ipLong = ipToLongFast(ip);
            long startLong = ipToLongFast(startIP);
            long endLong = ipToLongFast(endIP);
            return ipLong >= startLong && ipLong <= endLong;
        } catch (Exception e) {
            return false;
        }
    }
    
    /**
     * 快速将IP地址转换为长整型
     */
    private long ipToLongFast(String ipAddress) {
        String[] parts = ipAddress.split("\\.");
        long result = 0;
        for (int i = 0; i < 4; i++) {
            result = result << 8 | Integer.parseInt(parts[i]);
        }
        return result;
    }
    
    /**
     * 快速获取推荐的IP地址
     */
    private String getRecommendedIPFast(List<Map<String, String>> ipList) {
        if (ipList.isEmpty()) {
            return "127.0.0.1";
        }
        
        // 优先选择内网IP
        for (Map<String, String> ipInfo : ipList) {
            if ("内网".equals(ipInfo.get("type"))) {
                return ipInfo.get("ip");
            }
        }
        
        // 如果没有内网IP，选择第一个非特殊IP
        for (Map<String, String> ipInfo : ipList) {
            if (!"特殊".equals(ipInfo.get("type"))) {
                return ipInfo.get("ip");
            }
        }
        
        // 如果都没有，返回第一个IP
        return ipList.get(0).get("ip");
    }
}
